﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using FrameWork.Lib;
using FrameWork.Lib.DataObjects;
using System.Threading.Tasks;

namespace REVISIONMAX30
{
    public partial class frmGroup : DockContent
    {
        public frmGroup()
        {
            InitializeComponent();
        }

        public UIManager UIManager { get; set; }
        public DataObjects.Group Group { get; set; }
        public DataObjects.Data Data { get; set; }
        public DataObjects.Group OriginalGroup { get; set; }
        public System.Threading.Thread ExecuteBatchThread;
 
        public void View(DataObjects.Group pChildObject, DataObjects.Data pParentObject)
        {
            this.mySQLItemList.UIManager = this.UIManager;
            this.mySourceList.UIManager = this.UIManager;
            this.myLogList.UIManager = this.UIManager;
            this.myConnectionStringList.UIManager = this.UIManager;

            this.OriginalGroup = pChildObject;
            this.Group = this.OriginalGroup.Clone();
            this.Data = pParentObject;
            this.UpdateViewer();
 
        }

        public void UpdateViewer()
        {
            this.txtGroupName.Text = this.Group.GroupName;
            this.txtCurrentRevision.Text = this.Group.CurrentRevision.StringValueOrEmpty();

            this.btnDelete.Enabled = this.UIManager.Data.GroupList.Exists(t => t.DataObjectGUID == this.Group.DataObjectGUID);

            this.mySQLItemList.Init(this.Group);

            this.mySourceList.Init(this.Group);
            this.myLogList.Init(this.Group);
            this.myConnectionStringList.Init(this.Group);
        }

        private void UpdateObject()
        {
            this.Group.GroupName = this.txtGroupName.Text;
            this.Group.CurrentRevision = this.txtCurrentRevision.Text.IntValueOrZero();
        }

        public Guid DataObjectGUID
        {
            get { return this.Group.DataObjectGUID; }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            this.Save(true);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("are you sure you want to delete this Group?", "are you sure you want to delete this Group?", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                this.UIManager.Data.GroupList.Remove(this.Group);
                this.UIManager.GroupListPanel.UpdateViewer();
                base.Close();
            }
        }

        private void btnDumpDBsToBackup_Click(object sender, EventArgs e)
        {
            var tResult = this.Group.DumpDBsToBackUp();
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            btnExecute.Enabled = false;
            ExecuteBatchThread = new System.Threading.Thread(new System.Threading.ThreadStart(ExecuteBatch));
            ExecuteBatchThread.Start();
        }

        private void ExecuteBatch()
        {
            ExecutionEnabled(false);

            var revision = this.Group.CurrentRevision;

            if (revision == 0) revision = -1;

            var sqlitems = this.Group.SQLItemList.Where(j => j.Expired == null && j.Revision > revision).OrderBy(t => t.Revision).ThenBy(t => t.ExecutionOrderIndex).ThenBy(t => t.SelectedConnectionStringName);

            this.Group.ExecuteSQLItems(UIManager.EventManager, new EventManager.DelegateAddOrUpdateItem<DataObjects.SQLItem>(mySQLItemList.AddOrUpdateItem), sqlitems);

            ExecutionEnabled(true);
        }

        public delegate void DelegateEnable(bool enable);

        public void ExecutionEnabled(bool enabled)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new DelegateEnable(ExecutionEnabled), enabled);
            }
            else
            {
                btnExecute.Enabled = enabled;
                btnDumpDBsToBackup.Enabled = enabled;
                btnUpdate.Enabled = enabled;
                btnReset.Enabled = enabled;

                mySQLItemList.ExecutionEnabled(enabled);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            Parallel.ForEach(this.Group.SQLItemList, sqlitem => { sqlitem.Executed = null; sqlitem.LastExecutionResult = null; });

            UpdateViewer();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            this.Save(false);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {

            this.Group.UpdateSQLItemsFromSourceDirectories();

            this.UpdateViewer();
        }

        private void Save(bool apply)
        {
            this.UpdateObject();

            if (!this.Data.GroupList.Exists(t => t.DataObjectGUID == this.Group.DataObjectGUID))
            {
                this.Data.GroupList.Add(this.Group);
            }
            else
            {
                this.Group.Updated = DateTime.Now;
                this.Data.GroupList.RemoveAll(t => t.DataObjectGUID == this.Group.DataObjectGUID);
                this.Data.GroupList.Add(this.Group);
            }

            this.UIManager.GroupListPanel.UpdateViewer();
            this.OriginalGroup = this.Group.Clone();

            if (!apply)
            {
                base.Close();
            }
            else
            {
                UpdateViewer();
            }

        }

        private void tabMain_TabIndexChanged(object sender, EventArgs e)
        {
            if (this.tabMain.SelectedTab == this.tabSQLItems)
            {
                this.mySQLItemList.UpdateViewer();
            }
            else if (this.tabMain.SelectedTab == this.tabSources)
            {
                this.mySourceList.UpdateViewer();
            }
            else if (this.tabMain.SelectedTab == this.tabLogs)
            {
                this.myLogList.UpdateViewer();
            }
            else if (this.tabMain.SelectedTab == this.tabSQLItems)
            {
                this.myConnectionStringList.UpdateViewer();
            }
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            this.Text = "Group: " + this.txtGroupName.Text + " " + this.txtCurrentRevision.Text;
        }

        private void txtRevision_TextChanged(object sender, EventArgs e)
        {
            this.Text = "Group: " + this.txtGroupName.Text + " " + this.txtCurrentRevision.Text;
        }

        private void frmGroup_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.OriginalGroup.ToXml() != this.Group.ToXml())
            {
                if (MessageBox.Show("do you want to save changes to the group?", "unsaved changes", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    Save(true);
                }
            }
        }
    }
}
